package com.tuozixuan.caffeine;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;

/**
 * 术语
 * 驱逐: 缓存元素因为策略被移除
 * 失效: 缓存元素被手动移除
 * 移除: 由于驱逐或者失效而最终导致的结果
 */
public class RemovalDemo {

	public static void main(String[] args) {
		
		Cache<String, String> cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES)
				.maximumSize(10_000)
				.evictionListener((String key, String value, RemovalCause cause) -> System.out.println("[Eviction]key:" + key + " value:" + value + " cause:" + cause))
				.removalListener((k, v, c) -> System.out.println("[Remove]key:" + k + " value:" + v + " cause:" + c))
				.build();
		
		String key = "name";
		cache.put(key, "lisi");
		
		String name = cache.getIfPresent(key);
		System.out.println("name:" + name);
		
		// 失效key
		cache.invalidate(key);
		// 批量失效key
		cache.invalidateAll(Arrays.asList(key));
		// 失效所有的key
		cache.invalidateAll();
		
		name = cache.getIfPresent(key);
		System.out.println("name:" + name);
		
	}

}
